<script type="text/javascript" language="javascript" src="<?php echo base_url(); ?>public/js/jquery.validate.js"></script>
<script src="<?php echo base_url(); ?>public/js/chosen.jquery.min.js" type="text/javascript"></script>
<script src="<?php echo base_url(); ?>public/js/ajax-chosen.min.js" type="text/javascript"></script>
<script src="<?php echo base_url(); ?>public/js/validation-custom-text.js" type="text/javascript"></script>
<script type="text/javascript">
    // Declare datatable and officer id
    var officer_ID  = 0,  omrTable, isOfficerAdd = true;
    $(document).ready(function(){
        
        // change button to add by default (add/update)
        changeOfficerForm();
        
        // chosen for officer function query
        $("#sofficial_function").change(function(){ 
            oTable.fnReloadAjax("<?php echo base_url(); ?>index.php/medal_receipt/officer?" + $('#search-officer-form').serialize()); 
        }).chosen();     
        $("#function").chosen();
        
        // ajax chosen for officer medal
        $("#medalofficer").ajaxChosen({
            method: 'GET',
            url: '<?php echo base_url(); ?>index.php/medal_receipt/medal_list',
            dataType: 'json'
        }, function (data) {
            var terms = {};			
            $.each(data, function (i, val) {
                terms[val.ID] = val.full_name;
            });			
            return terms;
        }); 
        
        // ajax chosen for official order
        $("#official_order").ajaxChosen({
            method: 'GET',
            url: '<?php echo base_url(); ?>index.php/official_order/official_list',
            dataType: 'json'
        }, function (data) {
            var terms = {};			
            $.each(data, function (i, val) {
                terms[val.ID] = val.Order_Number;
            });			
            return terms;
        }); 
        
        //ajax chosen for officer
        $("#sofficial_name").ajaxChosen({
            method: 'GET',
            url: '<?php echo base_url(); ?>index.php/officer/officer_list',
            dataType: 'json'
        }, function (data) {
            var terms = {};		
            
            $.each(data, function (i, val) {
                terms[val.ID] = val.name;
            });			
            return terms;
        }).change(function(){ 
            oTable.fnReloadAjax("<?php echo base_url(); ?>index.php/medal_receipt/officer?" + $('#search-officer-form').serialize()); 
        }); 
        
        //submit officer form
        $("#frm-officer").ajaxForm({
            beforeSubmit: function(){
                // validate
                validateDefaultText('#frm-officer input');
                var validate = $('#frm-officer').validate().form();
                if (validate == false){
                    returnDefaultText('#frm-officer input');
                    validate.error();
                    return false; 
                }
                // Waiting
                $('#form-add-officer .loading').show();
                $('#form-add-officer .add-button').addClass('disable-add-button');
                $('#form-add-officer .update-button').addClass('disable-update-button');
                $('#form-add-officer .add-button, #form-add-officer .update-button').attr('disabled', 'disabled');
            },
            url: '<?php echo base_url(); ?>index.php/medal_receipt/do_new_recept',
            dataType: 'json',
            error: function(){                
                // stop waiting display error
                $('#form-add-officer .err-msg').html("ទិន្នន័យមិនអាចរក្សាទុកបានដោយបញ្ហាបច្ចេកទេស");                
                $('#form-add-officer .loading').hide();
                $('#form-add-officer .add-button').removeClass('disable-add-button');
                $('#form-add-officer .update-button').removeClass('disable-update-button');
                $('#form-add-officer .add-button, #form-add-officer .update-button').removeAttr('disabled');
            },
            success: function (data){                
                if (!data.result){
                    // data invalide
                    $('#form-add-officer .err-msg').html(data.message);
                }else{            
                    // save success
                    oTable.fnDraw(false);
                    clearOfficer();
                    changeOfficerForm();
                    $('#form-add-officer .err-msg').html(data.message);
                }
                // Stop waiting
                $('#form-add-officer .loading').hide();
                $('#form-add-officer .add-button').removeClass('disable-add-button');
                $('#form-add-officer .update-button').removeClass('disable-update-button');
                $('#form-add-officer .add-button, #form-add-officer .update-button').removeAttr('disabled');
            }
        });
        
        // submit officer reception
        $("#frm-receipt").ajaxForm({
            beforeSerialize: function(){          
                // target officer before submit
                $("#frm-receipt #officialname").val(officer_ID);  
            },
            beforeSubmit: function(){
                // check if selected officer
                if(officer_ID == 0){
                    return false;
                }
                // validate
                validateDefaultText('#frm-receipt input');
                var validate = $('#frm-receipt').validate().form();
                if (validate == false){
                    returnDefaultText('#frm-receipt input');
                    validate.error();
                    return false; 
                }
                // Waiting
                $('#form-add-receipt .loading').show();
                $('#form-add-receipt .add-button').addClass('disable-add-button').attr('disabled', 'disabled');
            },
            url: '<?php echo base_url(); ?>index.php/official_order/add_medal_reception',
            error: function(){                
                // stop waiting display error
                $('#form-add-receipt .err-msg').html("ទិន្នន័យមិនអាចរក្សាទុកបានដោយបញ្ហាបច្ចេកទេស");                
                $('#form-add-receipt .loading').hide();
                $('#form-add-receipt .add-button').removeClass('disable-add-button').removeAttr('disabled');
            },
            dataType: 'json',
            success: function (data){                
                if (!data.result){
                    // data invalide
                    $('#form-add-receipt .err-msg').html(data.message);
                }else{            
                    // success
                    $('#form-add-receipt .err-msg').html(data.message);
                    omrTable.fnReloadAjax("<?php echo base_url(); ?>index.php/medal_receipt/receipt?officer_ID=" + officer_ID); 
                }
                // stop waiting display
                $('#form-add-receipt .loading').hide();
                $('#form-add-receipt .add-button').removeClass('disable-add-button').removeAttr('disabled');
            }
        });
        
        // add event handler to edit officer
        $(".edit-officer").live('click', function(event){
            event.preventDefault();
            $("#officerid").val($(this).attr("rel"));
            isOfficerAdd = false;
            officer_ID = 0 ;
            changeOfficerForm();
            officerReadData();            
        });
        
        // datatable for officer
        var oTable = $('#officer-table').dataTable( {
            "bSortClasses": false,
            "bPaginate": true,
            "bLengthChange": true,
            "bFilter": false,
            "bSort": true,
            "bInfo": false,
            "bAutoWidth": false,
            "aoColumns" : [
                { sWidth: '30px' },
                { sWidth: '200px' },
                { sWidth: '250px' },
                { sWidth: '20px' }
            ] ,
            "aoColumnDefs": [ 
                { "bSortable": false, "aTargets": [ 0, 3, 4 ] }
            ],
            "aaSorting": [[ 1, "asc" ]],
            "bProcessing": true,
            "bServerSide": true,
            "sAjaxSource": "<?php echo base_url(); ?>index.php/medal_receipt/officer?" + $('#search-officer-form').serialize(),
            "fnDrawCallback": function( oSettings ) {
                clearOfficer();               
                officer_ID = 0;  
                isOfficerAdd = true;
                omrTable.fnReloadAjax("<?php echo base_url(); ?>index.php/medal_receipt/receipt?officer_ID=" + officer_ID); 
            }
        });
        
        // datatable for reception
        omrTable = $('#receipt-list').dataTable( {
            "bSortClasses": false,
            "bPaginate": true,
            "bLengthChange": true,
            "bFilter": false,
            "bSort": true,
            "bInfo": false,
            "bAutoWidth": false,
            "aoColumns" : [
                { sWidth: '30px' },
                { sWidth: '200px' },
                { sWidth: '180px' },
                { sWidth: '100px' },
                { sWidth: '100px' },
                { sWidth: '20px' }
            ] ,
            "aoColumnDefs": [ 
                { "bSortable": false, "aTargets": [ 0, 5 ] }
            ],
            "aaSorting": [[ 1, "asc" ]],
            "bProcessing": true,
            "bServerSide": true, 
            "fnDrawCallback": function( oSettings ) {
                clearReceipt();     
            },
            "sAjaxSource": "<?php echo base_url(); ?>index.php/medal_receipt/receipt?officer_ID=" + officer_ID
        });
        
        // add event handler to cancel update officer
        $("#officer-cancel").click(function(event) {
            event.preventDefault();
            clearOfficer();
            changeOfficerForm();
        });
        
        // add event handler to delete officer
        $(".delete-officer").live('click', function(event){
            event.preventDefault();
            var id = $(this).attr("rel");
            if(confirm("តើពិតជាចង់លុបមែនរឺ")){
                var url = "<?php echo base_url(); ?>index.php/medal_receipt/delete_officer";
                var data = "ID=" + id;
                $.post(url, data, function(callback){     
                    if (!callback.result){
                        $('#form-add-officer .err-msg').html(callback.message);
                    }else{   
                        $('#form-add-officer .err-msg').html(callback.message);         
                        oTable.fnReloadAjax("<?php echo base_url(); ?>index.php/medal_receipt/officer?" + $('#search-officer-form').serialize()); 
                    }
                }, "json");
            }
        });
        
        // add event handler to medal reception
        $(".delete-medal-reception").live('click', function(event){
            event.preventDefault();
            var id = $(this).attr("rel");
            if(confirm("តើពិតជាចង់លុបមែនរឺ")){
                var url = "<?php echo base_url(); ?>index.php/official_order/delete_medal_reception";
                var data = "ID=" + id;
                $.post(url, data, function(callback){     
                    if (!callback.result){
                        $('#frm-receipt .err-msg').html(callback.message);
                    }else{   
                        $('#frm-receipt .err-msg').html(callback.message);         
                        omrTable.fnReloadAjax("<?php echo base_url(); ?>index.php/medal_receipt/receipt?officer_ID=" + officer_ID); 
                    }
                }, "json");
            }
        });
        
        // add select available for officer datatable
        $("#officer-table tbody").click(function(event) {
            $(oTable.fnSettings().aoData).each(function (){
                $(this.nTr).removeClass('row_selected');
            });
            $(event.target.parentNode).addClass('row_selected');
            officer_ID = $(event.target.parentNode).find(".edit-officer").attr("rel");
            omrTable.fnReloadAjax("<?php echo base_url(); ?>index.php/medal_receipt/receipt?officer_ID=" + officer_ID); 
        });
    });	
    
    // when change from add -> update or update -> add
    function changeOfficerForm(){
        if(isOfficerAdd){
            $("#officer-update, #officer-cancel").hide();
            $("#official_submit").show();
        }else{
            $("#officer-update, #officer-cancel").show();
            $("#official_submit").hide();            
        }
    }
    
    // reset form officer after crud operation
    function clearOfficer(){   
        isOfficerAdd = true;
        officer_ID = 0;
        $("#form-add-officer .err-msg").html("");  
        $("#frm-officer #officerid").val(officer_ID);  
        $('#frm-officer select').val("").trigger("liszt:updated");
        $('#frm-officer #official_note').val("សំគាល់​");
        $('#frm-officer #official_name').val("ឈ្មោះ​");
        $('#frm-officer .populated-text').each(function () {
            populateText($(this));
        }); 
    }
    
    // reset form medal reception after crud operation
    function clearReceipt(){        
        $("#form-add-receipt .err-msg").html("");  
        $("#frm-receipt select").val("").trigger("liszt:updated");  
        $("#frm-receipt #receptiondate").val("កាលបរិច្ឆេទ​");  
        $('#frm-receipt .populated-text').each(function () {
            populateText($(this));
        }); 
    }
    
    // read officer by officer id to form
    function officerReadData(){
        var id = $("#officerid").val(); 
        $.ajax({
            url: "<?php echo base_url(); ?>index.php/medal_receipt/read_officer",
            data : "id="+id,
            type: "POST",
            dataType: "json",
            success: function(result){
                $("#function").val(result.function_ID).trigger("liszt:updated");
                $("#official_name").val(result.name);
                if($.trim(result.note) != ""){
                    $("#official_note").val(result.note);
                }                
                setDataEntered($("#form-add-officer")); 
            }               
        });
    }
</script>
<div id="left-content">
    <div id="official" class="content-block">
        <div class="block-header">មន្រ្តីរាជការ</div>
        <div id="block-content">
            <div id="search-panel">
                <form method="post" autocomplete="off" name="search-officer-form" id="search-officer-form" enctype="multipart/form-data">
                    <fieldset>
                        <legend>ស្វែងរក</legend>
                        <select id="sofficial_name" name="sofficial_name" style="width: 192px;" />
                        <option value="">ឈ្មោះមន្ត្រីរាជការ</option>
                        <?php foreach ($officers as $officer) { ?>
                            <option value="<?= $officer['ID'] ?>" ><?= $officer['name'] ?></option>
                        <?php } ?>
                        </select>
                        <select id="sofficial_function" name="sofficial_function"/>
                        <option value="">ឋានៈ​</option>
                        <?php foreach ($officer_functions as $officer_function) { ?>
                            <option value="<?= $officer_function['ID'] ?>" ><?= $officer_function['name'] ?></option>
                        <?php } ?>
                        </select>
                    </fieldset>
                </form>
            </div>
            <table id="officer-table" class="no-vertical-border bedatable">
                <thead>
                    <tr>
                        <th class="index-col">ល.រ</th>
                        <th >ឋានៈ​</th>
                        <th >ឈ្មោះ</th>
                        <th align="center" class="blank-header" ></th>
                        <th align="center" class="blank-header" ></th>
                    </tr>
                </thead>
            </table>
            <div class="break"></div>
            <div id="form-add-officer" class="form-add-panel">
                <div id="title">បញ្ជូលមន្ត្រីថ្មី៖</div>
                <div class="err-msg"></div>
                <div class="loading"><img src="<?php echo base_url(); ?>public/images/forms/loading-bar.gif" /></div>
                <form method="post" autocomplete="off" action="#" name='frm-officer' id="frm-officer" >
                    <select id="function" name="function" class="required"/>
                    <option value="" >ឋានៈ​</option>
                    <?php foreach ($officer_functions as $officer_function) { ?>
                        <option value="<?= $officer_function['ID'] ?>" ><?= $officer_function['name'] ?></option>
                    <?php } ?>
                    </select>
                    <input type="text" name="name" id="official_name" value="ឈ្មោះ" class="text input required populated-text" />            
                    <input type="text" name="note" id="official_note" value="សំគាល់" class="text input required populated-text" />
                    <input type="hidden" value="0" name="officerid" id="officerid" />
                    <input type="submit" id="officer-cancel" name="officer-cancel" value="" class="cancel-button right" />
                    <input type="submit" id="officer-update" name="officer-update" value="" class="update-button right" />
                    <input type="submit" id="official_submit" value="" class="add-button" />
                    <div class="break"></div>
                </form>
            </div>
        </div>
    </div>
    <!-- medal receipt-->
    <!--<form method="post" action="#" name='frmAdd' >-->
    <div id="received-medal" class="content-block">
        <div class="block-header">មេដាយទទួលបាន</div>
        <div id="block-content">
            <table id="receipt-list" class="data-table" class="no-vertical-border">
                <thead>
                    <tr>
                        <th class="index-col" >ល.រ</th>
                        <th>ប្រភេទ​</th>
                        <th>ថ្នាក់</th>
                        <th>លេខក្រឹត្យ</th>
                        <th>កាលបរិច្ឆេទ</th>
                        <th align="center" class="blank-header" ></th>
                    </tr>
                </thead>                
            </table>
            <div class="break"></div>
            <div id="form-add-receipt" class="form-add-panel">
                <div id="title">បញ្ជូលមេដាយបន្ថែម៖</div>
                <div class="err-msg"></div>
                <div class="loading"><img src="<?php echo base_url(); ?>public/images/forms/loading-bar.gif" /></div>
                <form method="post" action="#" autocomplete="off" name='frm-receipt' id="frm-receipt" >
                    <select id="medalofficer" name="medalofficer" class="required" />
                    <option value="" >ប្រភេទ/ថ្នាក់មេដាយ​</option>                  
                    <?php
                    foreach ($medals as $medal):
                        echo "<option value='{$medal['ID']}'>{$medal['full_name']}</option>";
                    endforeach;
                    ?>
                    </select>
                    <select id="official_order" name="official_order_ID" class="required" style="width: 200px;"/>
                    <option value="" >លេខក្រឹត្យ​</option>                
                    <?php
                    foreach ($official_orders as $official_order):
                        echo "<option value='{$official_order['ID']}'>{$official_order['Order_Number']}</option>";
                    endforeach;
                    ?>
                    </select>
                    <input type="hidden" id="officialname" name="officialname" />
                    <input type="submit" id="receipt_submit" value="" class="add-button" />
                    <input type="text" id="receptiondate"  value="កាលបរិច្ឆេទ​" name="receptiondate" class="required input text datepicker dateDefault populated-text" />
                </form>
            </div>
        </div>
    </div>
    <!--</form>-->
    <!--</div>
    <div id="related-activity" class="content-block right">
            <div class="block-header">ប្រតិបត្តិសំខាន់ៗ</div>
        <div id="block-content"></div>
    </div>-->